#include "mog_video_background_remove.h"

MOG_Video_Background_Remove::MOG_Video_Background_Remove(QWidget *parent)
    : CommonGraphicsView{parent}
{
    this->setWindowTitle("视频背景消除");
    this->setFixedSize(QSize(320,480));

    QPushButton *choiceVideo = new QPushButton(this);
    choiceVideo->setText("选择视频");
    connect(choiceVideo,&QPushButton::clicked,[=](){
        path = QFileDialog::getOpenFileName(this, tr("选择视频"), ".", tr("video Files(*.mp4 *.avi)"));
        const char *fileRealPath = path.toStdString().c_str();
        qDebug()<< "视频路径路径:"<<path;
    });

    //创建一组Group
    QButtonGroup *btnGroup  = new QButtonGroup(this);
    QRadioButton *btn1 = new QRadioButton(this);
    btn1->setText("MOG背景消除");
    btn1->move(0,choiceVideo->y()+choiceVideo->height()+20);

    QRadioButton *btn2 = new QRadioButton(this);
    btn2->move(btn1->x()+btn1->width()+20,choiceVideo->y()+choiceVideo->height()+20);
    btn2->setText("其他背景消除");
    btnGroup->addButton(btn1);
    btnGroup->setId(btn1,0);
    btnGroup->addButton(btn2);
    btnGroup->setId(btn2,1);

    connect(btn1,&QRadioButton::clicked,[=](bool flag){
        qDebug()<<"测试RadioButton的Id："<<btn1->text();
        if(path.isEmpty()){
            QMessageBox::warning(this,"警告","视频路径不能为空");
        }else{
            showMogBackgroundRemove(path.toStdString().c_str());
        }

    });
    connect(btn2,&QRadioButton::clicked,[=](bool flag){
        qDebug()<<"测试RadioButton的Id："<<btn2->text();
        if(path.isEmpty()){
            QMessageBox::warning(this,"警告","视频路径不能为空");
        }else{
            showKNNBackgroundRemove(path.toStdString().c_str());
        }
    });




}


void MOG_Video_Background_Remove::showMogBackgroundRemove(const char* filePath){
    VideoCapture capture;
    capture.open(filePath);
    if(!capture.isOpened()){
        qDebug()<<"无法打开视频文件";
        return;
    }
    Mat frame;
    Mat bsMaskMOG;
    Ptr<BackgroundSubtractor> mogSub = createBackgroundSubtractorMOG2(100,25,false);
    Mat kernel = getStructuringElement(MORPH_RECT,Size(3,3));
    while(capture.read(frame)){
        mogSub->apply(frame,bsMaskMOG);
        morphologyEx(bsMaskMOG,bsMaskMOG,MORPH_OPEN,kernel);//使用形态学操作消除白点
        imshow("mog",bsMaskMOG);
        imshow("frame",frame);
        waitKey(100);
    }
    capture.release();
}

void MOG_Video_Background_Remove::showKNNBackgroundRemove(const char* filePath){
    VideoCapture capture;
    capture.open(filePath);
    if(!capture.isOpened()){
        qDebug()<<"无法打开视频文件";
        return;
    }
    Mat frame;
    Mat knnMask;
    Mat kernel = getStructuringElement(MORPH_RECT,Size(3,3));
    Ptr<BackgroundSubtractor> knnSub = createBackgroundSubtractorKNN();
    while(capture.read(frame)){
        knnSub->apply(frame,knnMask);
        morphologyEx(knnMask,knnMask,MORPH_OPEN,kernel);
        imshow("knn",knnMask);
        waitKey(100);
    }
    capture.release();
}
